using Dapper;
using DataCapture.Helper;
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using static DataCapture.Helper.PublicHelp;

/// <summary>
/// 它负责数据库和编程语言之间的映射
/// Dapper更倾向于面向SQL，支持多种数据库。
/// 数据库的增删改查的工具类
/// </summary>
public class DapperHelper
{
    private static DapperHelper _instance;
    public bool isConnect { get; set; }//是否连接成功
    private static readonly object Padlock = new object();
    // 回调委托：参数1=是否成功，参数2=结果消息（成功信息/错误详情）
    public delegate void ConnectCallback(bool isSuccess, string message);
    private static string _connectionString = $"Data Source=10.25.3.90;port=3306;Database=dmes_hf;AllowLoadLocalInfile=true;User ID=admin;Password=admin;allowPublicKeyRetrieval=true;pooling=true;CharSet=utf8;sslmode=none;";//现场mes  id:ht;mima:Hf@Ht250822

    //private static string connectionString = $"Data Source=localhost;port=3306;Database=hf_data_collection;AllowLoadLocalInfile=true;User ID=root;Password=bao7980...;allowPublicKeyRetrieval=true;pooling=true;CharSet=utf8;sslmode=none;";//本地测试mes

    private DapperHelper()
    {

        _connectionString = ConfigurationHelper.GetAppSettings.ConnectionStrings.MESConnection;//配置表
        Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
    }
    /// <summary>
    /// 异步连接MySQL数据库
    /// </summary>
    /// <param name="connectionString">数据库连接字符串</param>
    /// <param name="callback">连接完成后的回调</param>
    public static async Task<bool> ConnectAsync(ConnectCallback callback=null)
    {
        MySqlConnection connection = null;
        try
        {
            // 创建连接对象
            connection = new MySqlConnection(_connectionString);
            // 异步打开连接（不阻塞UI线程）
            await connection.OpenAsync();

            // 连接成功，调用回调（传递成功状态）
            callback?.Invoke(true, "数据库连接成功！");
            return true;
        }
        catch (Exception ex)
        {
            // 捕获异常（如网络错误、密码错误等），调用回调传递失败信息
            callback?.Invoke(false, $"连接失败：{ex.Message}");
            
        }
        finally
        {
            // 无论成功与否，关闭连接（异步关闭）
            if (connection != null)
                await connection.CloseAsync();
            
        }
        return false;
    }
    public static DapperHelper Instance
    {
        get
        {
            lock (Padlock)
            {
                return _instance ??= new DapperHelper();
            }
        }
    }

    public IDbConnection Connection
    {
        get
        {
            try
            {
                var connection = new MySqlConnection(_connectionString);
                return connection;
            }
            catch (Exception e)
            {
                Log4NetHelper.Error($"数据库：{_connectionString}，连接异常：{e}", true);
                throw;
            }

        }
    }

    public static IDbConnection MakeNewConnection()
    {

        var connection = new MySqlConnection(_connectionString);
        connection.Open();
        return connection;
    }


    /// <summary>
    /// 添加.
    /// <typeparam name="T">实体类型.</typeparam>
    /// <param name="sql">传入sql执行语句.</param>
    /// <param name="t">传入实体类型.</param>
    /// <returns>int.</returns>
    /// </summary>
    public static int Add<T>(string sql, T t)
        where T : class
    {
        using IDbConnection connection = _instance.Connection;
        return connection.Execute(sql, t);
    }

    /// <summary>
    /// 批量添加.
    /// </summary>
    /// <typeparam name="T">实体类型.</typeparam>
    /// <param name="sql">传入sql执行语句.</param>
    /// <param name="t">传入泛型类.</param>
    /// <returns>int.</returns>
    public static int Add<T>(string sql, List<T> t)
        where T : class
    {
        using IDbConnection connection = _instance.Connection;
        return connection.Execute(sql, t);
    }

    /// <summary>
    /// 删除.
    /// </summary>
    /// <typeparam name="T">实体类型.</typeparam>
    /// <param name="sql">传入sql执行语句.</param>
    /// <param name="t">传入实体类型.</param>
    /// <returns>int.</returns>
    public static int Delete<T>(string sql, T t)
        where T : class
    {
        using IDbConnection connection = _instance.Connection;
        return connection.Execute(sql, t);
    }

    /// <summary>
    /// 批量删除.
    /// </summary>
    /// <typeparam name="T">实体类型.</typeparam>
    /// <param name="sql">传入sql执行语句.</param>
    /// <param name="t">传入泛型类.</param>
    /// <returns>int.</returns>
    public static int Delete<T>(string sql, List<T> t)
        where T : class
    {
        using IDbConnection connection = _instance.Connection;
        return connection.Execute(sql, t);
    }

    /// <summary>
    /// 修改.
    /// </summary>
    /// <typeparam name="T">实体类型.</typeparam>
    /// <param name="sql">传入sql执行语句.</param>
    /// <param name="t">传入实体类型.</param>
    /// <returns>int.</returns>
    public static int Update<T>(string sql, T t)
        where T : class
    {
        using IDbConnection connection = _instance.Connection;
        return connection.Execute(sql, t);
    }

    /// <summary>
    /// 批量修改.
    /// </summary>
    /// <typeparam name="T">实体类型.</typeparam>
    /// <param name="sql">传入sql执行语句.</param>
    /// <param name="t">传入泛型类.</param>
    /// <returns>int.</returns>
    public static int Update<T>(string sql, List<T> t)
        where T : class
    {
        using IDbConnection connection = _instance.Connection;
        return connection.Execute(sql, t);
    }

    /// <summary>
    /// 查询.
    /// </summary>
    /// <typeparam name="T">实体类型.</typeparam>
    /// <param name="sql">传入sql执行语句.</param>
    /// <returns>泛型类.</returns>
    public static List<T> Query<T>(string sql)
        where T : class
    {
        using IDbConnection connection = _instance.Connection;
        return connection.Query<T>(sql).ToList();
    }

    /// <summary>
    /// 查询指定数据.
    /// </summary>
    /// <typeparam name="T">实体类型.</typeparam>
    /// <param name="sql">传入sql执行语句.</param>
    /// <param name="t">传入泛型类.</param>
    /// <returns>类.</returns>
    public static T Query<T>(string sql, T t)
        where T : class
    {
        using IDbConnection connection = _instance.Connection;
        return connection.Query<T>(sql, t).SingleOrDefault();
    }

    /// <summary>
    /// 查询的in操作.
    /// </summary>
    /// <typeparam name="T">实体类型.</typeparam>
    /// <param name="sql">传入sql执行语句.</param>
    /// <returns>泛型类.</returns>
    public static List<T> Query<T>(string sql, int[] ids)
        where T : class
    {
        using IDbConnection connection = _instance.Connection;
        return connection.Query<T>(sql, new { ids }).ToList();
    }
    /// <summary>
    /// 查询单个数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="sql"></param>
    /// <param name="t"></param>
    /// <returns></returns>
    public static dynamic QuerySingle<T>(string sql, T t) where T : class
    {
        using IDbConnection connection = _instance.Connection;
        dynamic result = null;
        try
        {
            result = connection.QuerySingle(sql, t);
        }
        catch (Exception ex)
        {
            Log4NetHelper.Error($"【DapperHelper】{ex}&&找不到数据 {sql} {t}");
        }
        return result;
    }
}